//
//  VisaNeedDetailViewController.m
//  MyTravel
//
//  Created by Hunk on 11-6-12.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "VisaNeedDetailViewController.h"
#import "NetworkManager.h"
#import "NSString+URLEncoding.h"
#import "MyLoadingView.h"

#define SEPARATEDBYSTRING (@"[OVER]")

@interface VisaNeedDetailViewController (Private)

-(void)addLabelOnCell:(UITableViewCell*)cell 
				 text:(NSString*)text
				frame:(CGRect)frame 
			  bgColor:(UIColor*)bgColor 
			textColor:(UIColor*)textColor 
		   fontOfSize:(UIFont*)fontOfSize 
		lineBreakMode:(UILineBreakMode)lineBreakMode
		textAlignment:(UITextAlignment)textAlignment;
@end

@implementation VisaNeedDetailViewController
@synthesize visaNeedStatus, countryId, visaType;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    SAFE_RELEASE(visaNeedArray)
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Init data 
    visaNeedArray = [[NSMutableArray alloc] init];
    
    NetworkRequestType requestType;
    
    switch (visaNeedStatus)
    {
        case VISANEEDSTATUS_PERSONALIDENTIFICATION:
        {   
            requestType = NetworkRequest_GetVisaNeedPersonalId;
        }
            break;  
        case VISANEEDSTATUS_PROTERTY:
        {
            requestType = NetworkRequest_GetVisaNeedProperty;
        }
            break;
        case VISANEEDSTATUS_EMPLOYMENT:
        {
            requestType = NetworkRequest_GetVisaNeedEmployment;
        }
            break;
        case VISANEEDSTATUS_STUDENTSCHILDREN:
        {
            requestType = NetworkRequest_GetVisaNeedStudentChildren;
        }
            break;
        case VISANEEDSTATUS_ELDERLY:
        {
            requestType = NetworkRequest_GetVisaNeedElderly;
        }
            break;
        case VISANEEDSTATUS_OTEHRS:
        {
            requestType = NetworkRequest_GetVisaNeedOthers;
        }
            break;
        default:
            break;
    }
    
    // NetworkRequest
    int nVisaType = 0;
    if([visaType isEqualToString:@"旅游签证"]) nVisaType = 1;
    else if([visaType isEqualToString:@"旅游签证-北京"]) nVisaType = 2;
    else if([visaType isEqualToString:@"旅游签证-上海"]) nVisaType = 3;
    else if([visaType isEqualToString:@"旅游签证-广州"]) nVisaType = 4;
    
    else if([visaType isEqualToString:@"商务签证"]) nVisaType = 5;
    else if([visaType isEqualToString:@"商务签证-北京"]) nVisaType = 6;
    else if([visaType isEqualToString:@"商务签证-上海"]) nVisaType = 7;
    else if([visaType isEqualToString:@"商务签证-广州"]) nVisaType = 8;
    
    else if([visaType isEqualToString:@"探亲访友"]) nVisaType = 9;
    else if([visaType isEqualToString:@"探亲访友-北京"]) nVisaType = 10;
    else if([visaType isEqualToString:@"探亲访友-上海"]) nVisaType = 11;
    else if([visaType isEqualToString:@"探亲访友-广州"]) nVisaType = 12;
    else 
        nVisaType = 0;
    
    NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                [countryId URLEncodedString], @"countryId", 
                                [NSString stringWithFormat:@"%d", nVisaType], @"visaType", nil];
    
    [[NetworkManager sharedNetworkManager] requestServerForMethod:requestType
                                                   WithParameters:parameters
                                                 AndCallBackScope:self
                                                    AndSuccessSel:@"onSuccess:"
                                                     AndFailedSel:@"onFailed:"];
    
    // Loading view
    [[MyLoadingView sharedMyLoadingView] startLoadingAnimation];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [visaNeedArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if([visaNeedArray count])
    {   
        NSString* textString = [visaNeedArray objectAtIndex:section];
        if([textString length])
        {
            //  NSLog(@"%@\n", textString);
            
            //  NSArray* array = [textString componentsSeparatedByString:SEPARATEDBYSTRING];
            //   NSLog(@"%d\n", [array count]);
            return [[[visaNeedArray objectAtIndex:section] componentsSeparatedByString:SEPARATEDBYSTRING] count];
        }
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    NSString* infoString = [visaNeedArray objectAtIndex:indexPath.section];
    if([infoString length])
    {
        NSArray* array = [infoString componentsSeparatedByString:SEPARATEDBYSTRING];
        
        CGSize size = [[array objectAtIndex:indexPath.row] sizeWithFont:[UIFont systemFontOfSize:16.0] 
                             constrainedToSize:CGSizeMake(300, 500)        
                                 lineBreakMode:UILineBreakModeCharacterWrap];
        
        return (size.height + 10.0f);
    }
    return 0.0f;    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    NSString* testString = [visaNeedArray objectAtIndex:section];
    
    NSArray* tempArray = [testString componentsSeparatedByString:SEPARATEDBYSTRING];

    if([tempArray count])
    {
        NSString* tempString = [tempArray objectAtIndex:0];
    
        return [tempString length] ? 30.0f : 0.0f;
    }
    return 30.0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    switch (visaNeedStatus)
    {
        case VISANEEDSTATUS_PERSONALIDENTIFICATION:
        {
            switch (section)
            {
                case 0:
                    return @"护照"; // passportInfo
                    break;
                case 1:
                    return @"照片"; // picturesInfo
                    break;
                case 2:
                    return @"名片"; // nameCardInfo
                    break;
                case 3:
                    return @"户口本"; // registeredResidence
                    break;
                case 4:
                    return @"身份证"; // personId
                    break;
                case 5:
                    return @"结婚证"; // marriageCertificate
                    break;
                case 6:
                    return @"其它"; // others
                    break;
                default:
                    break;
            }
        }
            break; 
        case VISANEEDSTATUS_PROTERTY:
        {
            switch (section)
            {
                case 0:
                    return @"存款证明"; // Property
                    break;
                case 1:
                    return @"房产证明"; // houseProperty
                    break;
                case 2:
                    return @"车产证明"; // carProperty
                    break;
                case 3:
                    return @"其它";
                    break;
                default:
                    break;
            }
        }
            break; 
        case VISANEEDSTATUS_EMPLOYMENT:
        {
            switch (section)
            {
                case 0:
                    return @"营业执照"; // businessLicense
                    break;
                case 1:
                    return @"机构代码证"; // organizationCode
                    break;
                case 2:
                    return @"在职证明"; // employmentCertificate
                    break;
                case 3:
                    return @"邀请函"; // invitation
                    break;
                case 4:
                    return @"其它";
                    break;
                default:
                    break;
            }
        }
            break;
        case VISANEEDSTATUS_STUDENTSCHILDREN:
        {
            switch (section)
            {
                case 0:
                    return @"公证书"; // notarialDeed
                    break;
                case 1:
                    return @"准假证明"; // leaveProof
                    break;
                case 2:
                    return @"其它";
                    break;
                default:
                    break;
            }
        }
            break;
        case VISANEEDSTATUS_ELDERLY:
        {
            switch (section)
            {
                case 0:
                    return @"辅助材料"; // auxiliaryMaterials
                    break;
                case 1:
                    return @"其它";
                    break;
                default:
                    break;
            }
        }
            break;
        case VISANEEDSTATUS_OTEHRS:
        {
            switch (section)
            {
                case 0:
                    return @"其它"; // others
                    break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
    
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                   reuseIdentifier:CellIdentifier] autorelease];
    
    NSString* testString = [visaNeedArray objectAtIndex:indexPath.section];
    
    NSArray* tempArray = [testString componentsSeparatedByString:SEPARATEDBYSTRING];
    
    CGSize size = [[tempArray objectAtIndex:indexPath.row] sizeWithFont:[UIFont systemFontOfSize:16.0] constrainedToSize:CGSizeMake(300, 500) lineBreakMode:UILineBreakModeCharacterWrap];
    
    // Cell background view
    UIView* cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, (size.height + 10))];
    UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, (size.height + 10))];
    [bgImageView setImage:[[UIImage imageNamed:@"CellBackground.png"]
                           stretchableImageWithLeftCapWidth:5 topCapHeight:5]];
    [cellBgView addSubview:bgImageView];
    [bgImageView release];
    [cell setBackgroundView:cellBgView];
    [cellBgView release];
    
    NSString* textString = [tempArray objectAtIndex:indexPath.row];
    
    // Content
    [self addLabelOnCell:cell
                    text:[NSString stringWithFormat:@"%d、%@", (indexPath.row + 1), textString]
                   frame:CGRectMake(10, 0, 300, (size.height + 10))
                 bgColor:[UIColor clearColor]
               textColor:TEXTCOLOR
              fontOfSize:[UIFont fontWithName:@"AmericanTypewriter" size:16]
           lineBreakMode:UILineBreakModeCharacterWrap
           textAlignment:UITextAlignmentLeft];
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -
#pragma mark NetworkManager callback Methods
- (void)onSuccess:(id)sender
{
    NSDictionary* resultDic = (NSDictionary*)sender;
    
    switch (visaNeedStatus)
    {
        case VISANEEDSTATUS_PERSONALIDENTIFICATION:
        {    
            NSDictionary* infoDic = [[resultDic objectForKey:@"visaNeedPersonalId"] objectAtIndex:0];
            
            [visaNeedArray addObjectsFromArray:[NSArray arrayWithObjects:
                                                [infoDic objectForKey:@"passportInfo"], 
                                                [infoDic objectForKey:@"picturesInfo"], 
                                                [infoDic objectForKey:@"nameCardInfo"], 
                                                [infoDic objectForKey:@"registeredResidence"], 
                                                [infoDic objectForKey:@"personId"], 
                                                [infoDic objectForKey:@"marriageCertificate"], 
                                                [infoDic objectForKey:@"others"], nil]];
        }
            break;  
        case VISANEEDSTATUS_PROTERTY:
        {
            NSDictionary* infoDic = [[resultDic objectForKey:@"visaNeedProperty"] objectAtIndex:0];
            
            [visaNeedArray addObjectsFromArray:[NSArray arrayWithObjects:
                                                [infoDic objectForKey:@"property"], 
                                                [infoDic objectForKey:@"houseProperty"],
                                                [infoDic objectForKey:@"carProperty"],
                                                [infoDic objectForKey:@"others"], nil]];
        }
            break;
        case VISANEEDSTATUS_EMPLOYMENT:
        {
            NSDictionary* infoDic = [[resultDic objectForKey:@"visaNeedEmployment"] objectAtIndex:0];
            
            [visaNeedArray addObjectsFromArray:[NSArray arrayWithObjects:
                                                [infoDic objectForKey:@"businessLicense"],
                                                [infoDic objectForKey:@"organizationCode"],
                                                [infoDic objectForKey:@"employmentCertificate"],
                                                [infoDic objectForKey:@"invitation"],
                                                [infoDic objectForKey:@"others"], nil]];
        }
            break;
        case VISANEEDSTATUS_STUDENTSCHILDREN:
        {
            NSDictionary* infoDic = [[resultDic objectForKey:@"visaNeedStudentChildren"] objectAtIndex:0];
            
            [visaNeedArray addObjectsFromArray:[NSArray arrayWithObjects:
                                                [infoDic objectForKey:@"notarialDeed"],
                                                [infoDic objectForKey:@"leaveProof"],
                                                [infoDic objectForKey:@"others"], nil]];
        }
            break;
        case VISANEEDSTATUS_ELDERLY:
        {
            NSDictionary* infoDic = [[resultDic objectForKey:@"visaNeedElderly"] objectAtIndex:0];
            
            [visaNeedArray addObjectsFromArray:[NSArray arrayWithObjects:
                                                [infoDic objectForKey:@"auxiliaryMaterials"],
                                                [infoDic objectForKey:@"others"], nil]];
        }
            break;
        case VISANEEDSTATUS_OTEHRS:
        {
            NSDictionary* infoDic = [[resultDic objectForKey:@"visaNeedOthers"] objectAtIndex:0];
            
            [visaNeedArray addObjectsFromArray:[NSArray arrayWithObjects:
                                                [infoDic objectForKey:@"others"], nil]];
        }
            break;
        default:
            break;
    }
    
    [self.tableView reloadData];
}

- (void)onFailed:(id)sender
{
    NSString* alertViewTitle = nil;
    
    switch (visaNeedStatus)
    {
        case VISANEEDSTATUS_PERSONALIDENTIFICATION:
        case VISANEEDSTATUS_PROTERTY:
        case VISANEEDSTATUS_EMPLOYMENT:
        {
            alertViewTitle = @"无需提供此款项材料";
        }
            break;
        case VISANEEDSTATUS_STUDENTSCHILDREN:
        {
            alertViewTitle = @"对学生及儿童暂无要求";
        }
            break;
        case VISANEEDSTATUS_ELDERLY:
        {
            alertViewTitle = @"对老年人暂无要求";
        }
            break;
        case VISANEEDSTATUS_OTEHRS:
        {
            alertViewTitle = @"暂无其它要求";
        }
            break;
        default:
            break;
    }
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:alertViewTitle
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}

#pragma mark -
#pragma mark addLabelOnCell
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark addLabelOnCell
-(void)addLabelOnCell:(UITableViewCell*)cell
				 text:(NSString*)text
				frame:(CGRect)frame 
			  bgColor:(UIColor*)bgColor 
			textColor:(UIColor*)textColor 
		   fontOfSize:(UIFont*)fontOfSize 
		lineBreakMode:(UILineBreakMode)lineBreakMode 
		textAlignment:(UITextAlignment)textAlignment
{
	if(!bgColor) bgColor = [UIColor grayColor];
	if(!textColor) textColor = [UIColor blackColor];
	if(!fontOfSize) fontOfSize = [UIFont systemFontOfSize:16];
	if(!text) text = [NSString stringWithString:@"请输入Label内容"];
	
	UILabel* titleLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
	titleLabel.backgroundColor = bgColor;
	titleLabel.textColor = textColor;
	titleLabel.font = fontOfSize;
	titleLabel.lineBreakMode = UILineBreakModeCharacterWrap;
	titleLabel.textAlignment = textAlignment;
    titleLabel.numberOfLines = 10;
	titleLabel.text = text;
	[cell.contentView addSubview:titleLabel];
}

@end
